{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import scipy.stats as sst\n",
    "import numpy as np\n",
    "import matplotlib.pylab as plt\n",
    "import matplotlib.pyplot as plot\n",
    "from matplotlib.widgets import Cursor\n",
    "import csv\n",
    "import math\n",
    "from matplotlib.font_manager import FontProperties\n",
    "from matplotlib.ticker import MultipleLocator\n",
    "from matplotlib.ticker import FormatStrFormatter\n",
    "import matplotlib.colors as colors\n",
    "import pandas as pd\n",
    "import matplotlib.mlab as mlab\n",
    "import seaborn as sns\n",
    "from sklearn import linear_model\n",
    "import matplotlib as mpl\n",
    "from matplotlib import patheffects\n",
    "import mpl_toolkits.axisartist.axislines as axislines\n",
    "from mpl_toolkits.axes_grid1.inset_locator import inset_axes\n",
    "from mpl_toolkits.axes_grid1.inset_locator import mark_inset\n",
    "import seaborn \n",
    "font_set = FontProperties(fname=r'C:\\windows\\fonts\\simsun.ttc',size=12)\n",
    "font_set1 = FontProperties(fname=r'C:\\windows\\fonts\\simsun.ttc',size=9)\n",
    "font_set1_1 = FontProperties(fname=r'C:\\windows\\fonts\\simsun.ttc',size=9.001)\n",
    "font_set1_2 = FontProperties(fname=r'C:\\windows\\fonts\\simsun.ttc',size=9.0001)\n",
    "font_set3 = FontProperties(fname=r'C:\\windows\\fonts\\simsun.ttc',size=7)\n",
    "font_set2 = FontProperties(fname=r'C:\\windows\\fonts\\simsun.ttc',size=6)\n",
    "font_set4 = FontProperties(fname=r'C:\\windows\\fonts\\simsun.ttc',size=8)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "#对升序序列找到对匹配val值最接近的点坐标\n",
    "def index_fit(y, val):\n",
    "    if val >= y[-1]:\n",
    "        return len(y) - 1\n",
    "    for i, yi in enumerate(y):\n",
    "        if val >= yi and val <= y[i + 1]:\n",
    "            if abs(val - yi) <= abs(val - y[ i + 1]):\n",
    "                fit_index = i\n",
    "            else:\n",
    "                fit_index = i+1\n",
    "            break\n",
    "    return fit_index\n",
    "\n",
    "#用于计算Lxx, Lyy\n",
    "def laa(x):\n",
    "    x_mean = np.mean(x)\n",
    "    lxx = np.sum((x-x_mean)**2)\n",
    "    return lxx\n",
    "\n",
    "#用于计算Lxy\n",
    "def lab(x,y):\n",
    "    x_mean = np.mean(x)\n",
    "    y_mean = np.mean(y)\n",
    "    lxy = np.sum((x-x_mean)*(y-y_mean))\n",
    "    return lxy\n",
    "\n",
    "#一元线性回归模型\n",
    "def polyfit_one(x, y, alpha):\n",
    "    if len(set(x))==1:\n",
    "        if len(set(y))==1:\n",
    "            poly_val=[999999,999999]\n",
    "            R=999999\n",
    "            R2=999999\n",
    "            pval=999999\n",
    "            linear_test=999999\n",
    "            poly_int=999999\n",
    "            lxx=999999\n",
    "            lyy=999999\n",
    "            lxy=999999\n",
    "            sigma_est=999999\n",
    "            x_mean=999999\n",
    "            y_mean=999999\n",
    "            test_level=999999\n",
    "            n=999999\n",
    "        else:\n",
    "            poly_val=[99999999,np.mean(x)]\n",
    "            R=999999\n",
    "            R2=999999\n",
    "            pval=999999\n",
    "            linear_test=999999\n",
    "            poly_int=999999\n",
    "            lxx=999999\n",
    "            lyy=999999\n",
    "            lxy=999999\n",
    "            sigma_est=999999\n",
    "            x_mean=999999\n",
    "            y_mean=999999\n",
    "            test_level=999999\n",
    "            n=999999\n",
    "    else:\n",
    "        assert len(x) == len(y)\n",
    "        n = len(x)\n",
    "        assert n > 2\n",
    "        lxx = laa(x)\n",
    "        lyy = laa(y)\n",
    "        lxy = lab(x, y)\n",
    "        R = lxy/(np.sqrt(lxx) * np.sqrt(lyy))\n",
    "        R2 = R*R   #计算相关系数与决定系数\n",
    "        \n",
    "        b_est = lxy/lxx  #计算b估计\n",
    "        x_mean = np.mean(x)\n",
    "        y_mean = np.mean(y)\n",
    "        a_est = y_mean - b_est * x_mean   #计算a估计\n",
    "        Qe = lyy - b_est * lxy\n",
    "        sigma_est2=(np.sum((y-a_est-b_est*x)**2))/(n-2)\n",
    "\n",
    "        sigma_est = np.sqrt(sigma_est2) #sigma估计\n",
    "        \n",
    "        test = np.abs(b_est * np.sqrt(lxx))/sigma_est\n",
    "        test_level = sst.t.ppf(1 - alpha/2, df=n - 2)\n",
    "        linear_test = test > test_level   #线性回归检验\n",
    "        pval = sst.t.sf(test,n-2)*2#计算p值\n",
    "\n",
    "        #a,b的置信区间\n",
    "        b_int = [b_est - test_level * sigma_est / np.sqrt(lxx), b_est + test_level * sigma_est / np.sqrt(lxx)]\n",
    "        a_int = [y_mean - b_int[1] * x_mean, y_mean - b_int[0] * x_mean]\n",
    "\n",
    "        poly_int = (a_int, b_int)\n",
    "\n",
    "        poly_val = (a_est, b_est)\n",
    "\n",
    "    #返回回归模型相应参数\n",
    "    test_val = {'R': R,\n",
    "                'R2': R2,\n",
    "                'Pvalue':pval,\n",
    "                'linear_test': linear_test,\n",
    "                'poly_int': poly_int,\n",
    "                }\n",
    "    process_val = {'lxx': lxx,\n",
    "                   'lyy': lyy,\n",
    "                   'lxy': lxy,\n",
    "                   'sigma_est': sigma_est,\n",
    "                   'x_mean': x_mean,\n",
    "                   'y_mean': y_mean,\n",
    "                   'test_level': test_level,\n",
    "                   'ndim': n,\n",
    "                   }\n",
    "    return (poly_val, test_val, process_val)\n",
    "\n",
    "#计算相应的预测区间\n",
    "def confidence_interval(y0=None, *args, **kwargs):\n",
    "    a_est, b_est = args\n",
    "    sigma_est = kwargs['sigma_est']\n",
    "    test_level= kwargs['test_level']\n",
    "    lxx = kwargs['lxx']\n",
    "    n = kwargs['ndim']\n",
    "    x_mean = kwargs['x_mean']\n",
    "\n",
    "    if isinstance(y0, (int, float, np.ndarray)):\n",
    "        x0 = (y0 - a_est) / b_est\n",
    "    elif isinstance(y0, (list, tuple)):\n",
    "        y0 = np.array(y0)\n",
    "        x0 = (y0 - a_est) / b_est\n",
    "    else:\n",
    "        return None\n",
    "\n",
    "    conf_down = y0 - test_level * sigma_est * np.sqrt(1 + 1 / n + ((x0 - x_mean) ** 2 / lxx))\n",
    "    conf_up = y0 + test_level * sigma_est * np.sqrt(1 + 1 / n + ((x0 - x_mean) ** 2 / lxx))\n",
    "\n",
    "    confidence_interval = (conf_down, conf_up)\n",
    "    return confidence_interval\n",
    "\n",
    "def LinearRegression (x,y,alpha):\n",
    "    poly_val,test_val, process_val = polyfit_one(x, y, alpha)\n",
    "    ytick_down = -500\n",
    "    ytick_up = 900#此处大于坐标轴最大值就行\n",
    "    Y_test = np.linspace(ytick_down, ytick_up, 1000000) #从ticks上下限间取1000000个点\n",
    "    X_test = (Y_test - poly_val[0]) / poly_val[1]#这些x_test和y_test组成的点在拟合线上\n",
    "    X_12 = Y_test / (5.893*1.8099)#p=pe线，第一、二区界限\n",
    "    X_34 = Y_test / (-5.893*1.8099)#p=-pe线，第三四区界限\n",
    "    Y_down, Y_up = confidence_interval(Y_test, *poly_val, **process_val)#相应预测区间的y值\n",
    "\n",
    "    regr1 = linear_model.LinearRegression()\n",
    "    regr1.fit(X_test.reshape(-1,1),Y_up)\n",
    "    d_up = regr1.intercept_\n",
    "    regr2 = linear_model.LinearRegression()\n",
    "    regr2.fit(X_test.reshape(-1,1),Y_down)\n",
    "    d_down = regr2.intercept_\n",
    "    return (d_up, d_down,Y_test,X_test,Y_up,Y_down,X_12, X_34)\n",
    "\n",
    "def select(xy,hull,a,b):\n",
    "    x=[]\n",
    "    y=[]\n",
    "    for i in range(a,b):\n",
    "        x.append(xy[hull[i],0])\n",
    "        y.append(xy[hull[i],1])\n",
    "    return np.array(x),np.array(y)\n",
    "def plotsca_tb(ax,tb_mean,x,y):\n",
    "    for i in range(len(tb_mean)):\n",
    "        if tb_mean[i]!=999999:\n",
    "            if y==1:\n",
    "                ax.scatter(x[i],tb_mean[i],s=5,c='r',marker='^',label='TB',alpha=0.7)\n",
    "                y=0\n",
    "            else:\n",
    "                ax.scatter(x[i],tb_mean[i],s=5,c='r',marker='^',alpha=0.7)\n",
    "\n",
    "\n",
    "def plotsca_E(ax,e_mean,x,y):\n",
    "    for i in range(len(e_mean)):\n",
    "        if e_mean[i]!=999999:\n",
    "            if y==1:\n",
    "                ax.scatter(x[i],e_mean[i],s=5,c='k',marker='o',label='E',alpha=0.7)\n",
    "                y=0\n",
    "            else:\n",
    "                ax.scatter(x[i],e_mean[i],s=5,c='k',marker='o',alpha=0.7)\n",
    "                \n",
    "\n",
    "def panduan(tb_mean):\n",
    "    z=0\n",
    "    for i in range(len(tb_mean)):\n",
    "        if tb_mean[i]==999999:\n",
    "            z=z+1\n",
    "    if z==len(tb_mean):\n",
    "        return 0\n",
    "    else:\n",
    "        return 1\n",
    "    \n",
    "def tuli(y):\n",
    "    x=[0,0,0,0]\n",
    "    for i in range(len(y)):\n",
    "        if y[i]==1:\n",
    "            x[i]=1\n",
    "            break\n",
    "    return x          "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "#从csv文件里面读取x,y\n",
    "def read_xy(file_path):\n",
    "    with open(file_path,encoding=\"gbk\") as fp:\n",
    "        csv_reader = csv.reader(fp)\n",
    "        x = []\n",
    "        y = []\n",
    "        check = []\n",
    "        p_pe=[]\n",
    "        p1_pe1=[]\n",
    "        p2_pe2=[]\n",
    "        p3_pe3=[]\n",
    "        p4_pe4=[]\n",
    "        p5_pe5=[]\n",
    "        p6_pe6=[]\n",
    "        p7_pe7=[]\n",
    "        p8_pe8=[]\n",
    "        p9_pe9=[]\n",
    "        p10_pe10=[]\n",
    "        p11_pe11=[]\n",
    "        p12_pe12=[]\n",
    "        dem=[]\n",
    "        p=[]\n",
    "        pe=[]\n",
    "        tp_year=[]\n",
    "        for ri,row in enumerate(csv_reader):\n",
    "            if ri == 0:\n",
    "                continue\n",
    "            x.append(float(row[3]))#tb\n",
    "            y.append(float(row[4]))#E\n",
    "            p_pe.append(float(row[5]))#tb\n",
    "            p1_pe1.append(float(row[6]))#tb\n",
    "            p2_pe2.append(float(row[7]))#tb\n",
    "            p3_pe3.append(float(row[8]))#tb\n",
    "            p4_pe4.append(float(row[9]))#tb\n",
    "            p5_pe5.append(float(row[10]))#tb\n",
    "            p6_pe6.append(float(row[11]))#tb\n",
    "            p7_pe7.append(float(row[12]))#tb\n",
    "            p8_pe8.append(float(row[13]))#tb\n",
    "            p9_pe9.append(float(row[14]))#tb\n",
    "            p10_pe10.append(float(row[15]))#tb\n",
    "            p11_pe11.append(float(row[16]))#tb\n",
    "            p12_pe12.append(float(row[17]))#tb\n",
    "            p.append(float(row[20]))#tb\n",
    "            pe.append(float(row[21]))#tb\n",
    "            dem.append(float(row[22]))#tb\n",
    "            tp_year.append(float(row[23]))#tb\n",
    "            check.append(float(row[1]))#value\n",
    "        total=int(float(row[26]))\n",
    "#             x = [round(i,5) for i in x]\n",
    "#             y = [round(i,5) for i in y]\n",
    "            \n",
    "    return np.array(x), np.array(y), np.array(check),np.array(p_pe),np.array(p1_pe1),np.array(p2_pe2),np.array(p3_pe3),np.array(p4_pe4),np.array(p5_pe5),np.array(p6_pe6),np.array(p7_pe7),np.array(p8_pe8),np.array(p9_pe9),np.array(p10_pe10),np.array(p11_pe11),np.array(p12_pe12),total,np.array(p),np.array(pe),np.array(dem),np.array(tp_year)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "def data_process(x,y,alpha):\n",
    "    n=total\n",
    "#Holdridge温度体系求占比\n",
    "    reserve_k_1 = []\n",
    "    reserve_k_2 = []\n",
    "    reserve_k_3 = []\n",
    "    reserve_k_4 = []\n",
    "    reserve_k_5 = []\n",
    "    reserve_k_6 = []\n",
    "    reserve_k_7 = []\n",
    "    for k, x[k] in enumerate(x):\n",
    "        if 0 <= x[k] < 1.5:#极地带\n",
    "            reserve_k_1.append(k)\n",
    "        elif 1.5 <= x[k] < 3:#亚极地带\n",
    "            reserve_k_2.append(k)\n",
    "        elif 3 <= x[k] < 6:#寒温带\n",
    "            reserve_k_3.append(k)\n",
    "        elif 6 <= x[k] < 10:#温带\n",
    "            reserve_k_4.append(k)\n",
    "        elif 10 <= x[k] < 14:#暖温带\n",
    "            reserve_k_5.append(k)\n",
    "        elif 14 <= x[k] < 22:#亚热带\n",
    "            reserve_k_6.append(k)    \n",
    "        else:#热带\n",
    "            reserve_k_7.append(k) \n",
    "\n",
    "    TB_max = max(x)\n",
    "    TB_min = min(x)\n",
    "    TB_mean = np.mean(x)\n",
    "    TB_std = np.std(x)\n",
    "    TB_mean_plus_std = TB_mean + TB_std\n",
    "    TB_mean_minus_std = TB_mean - TB_std\n",
    "    E_max = max(y)\n",
    "    E_min = min(y)\n",
    "    E_mean = np.mean(y)\n",
    "    E_std = np.std(y)\n",
    "    E_mean_plus_std = E_mean + E_std\n",
    "    E_mean_minus_std = E_mean - E_std       \n",
    "    center = (TB_mean,E_mean)#中心点位置坐标 \n",
    "    \n",
    "    DEM_max = max(dem)\n",
    "    DEM_min = min(dem)\n",
    "    DEM_mean = np.mean(dem)\n",
    "    DEM_std = np.std(dem)\n",
    "    DEM_mean_plus_std = DEM_mean + DEM_std\n",
    "    DEM_mean_minus_std = DEM_mean - DEM_std\n",
    "\n",
    "    p_max = max(p)\n",
    "    p_min = min(p)\n",
    "    p_mean = np.mean(p)\n",
    "    p_std = np.std(p)\n",
    "    p_mean_plus_std = p_mean + p_std\n",
    "    p_mean_minus_std = p_mean - p_std\n",
    "    \n",
    "    pe_max = max(pe)\n",
    "    pe_min = min(pe)\n",
    "    pe_mean = np.mean(pe)\n",
    "    pe_std = np.std(pe)\n",
    "    pe_mean_plus_std = pe_mean + pe_std\n",
    "    pe_mean_minus_std = pe_mean - pe_std\n",
    "    \n",
    "    tp_year_max = max(tp_year)\n",
    "    tp_year_min = min(tp_year)\n",
    "    tp_year_mean = np.mean(tp_year)\n",
    "    tp_year_std = np.std(tp_year)\n",
    "    tp_year_mean_plus_std = tp_year_mean + tp_year_std\n",
    "    tp_year_mean_minus_std = tp_year_mean - tp_year_std\n",
    "#开始分区\n",
    "    reserve_j_1 = []\n",
    "    reserve_j_2 = []\n",
    "    reserve_j_3 = []\n",
    "    reserve_j_4 = []\n",
    "    for j, xj in enumerate(x):#enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列，同时列出数据和数据下标，一般用在 for 循环当中。\n",
    "        if y[j] >= (5.893*1.8099) * x[j]:#第一区\n",
    "#             y[j] = '%0.5f'% y[j]\n",
    "            reserve_j_1.append(j)\n",
    "        elif 0 <= y[j]  < (5.893*1.8099) * x[j]:#第二区\n",
    "            reserve_j_2.append(j)\n",
    "        elif (-5.893*1.8099) * x[j] < y[j] < 0:#第三区\n",
    "            reserve_j_3.append(j)\n",
    "        else:#第四区\n",
    "            reserve_j_4.append(j) \n",
    "\n",
    "#第一区                \n",
    "    tb1 = x[reserve_j_1].tolist()#转成列表\n",
    "    E1 = y[reserve_j_1].tolist()  \n",
    "    n1 = len(reserve_j_1)\n",
    "    ratio1 = n1/n\n",
    "    total_1=n1/total\n",
    "#     print(p_pe[reserve_j_1].tolist())\n",
    "#对第一区内的点分成12个月均大于p>=pe和 12个月中存在小于p<pe\n",
    "    x1 = x[reserve_j_1]\n",
    "    y1 = y[reserve_j_1]\n",
    "    p_pe_1 = p_pe[reserve_j_1].tolist()\n",
    "    p1_pe1_1 = p1_pe1[reserve_j_1].tolist()\n",
    "    p2_pe2_1 = p2_pe2[reserve_j_1].tolist()\n",
    "    p3_pe3_1 = p3_pe3[reserve_j_1].tolist()\n",
    "    p4_pe4_1 = p4_pe4[reserve_j_1].tolist()\n",
    "    p5_pe5_1 = p5_pe5[reserve_j_1].tolist()\n",
    "    p6_pe6_1 = p6_pe6[reserve_j_1].tolist()\n",
    "    p7_pe7_1 = p7_pe7[reserve_j_1].tolist()\n",
    "    p8_pe8_1 = p8_pe8[reserve_j_1].tolist()\n",
    "    p9_pe9_1 = p9_pe9[reserve_j_1].tolist()\n",
    "    p10_pe10_1 = p10_pe10[reserve_j_1].tolist()\n",
    "    p11_pe11_1 = p11_pe11[reserve_j_1].tolist()\n",
    "    p12_pe12_1 = p12_pe12[reserve_j_1].tolist()\n",
    "    reserve_j_1_1 = []\n",
    "    reserve_j_1_2 = []\n",
    "    j=[]\n",
    "    for j,xj in enumerate(x1):\n",
    "        if p1_pe1_1[j]>=0 and p2_pe2_1[j]>=0 and p3_pe3_1[j]>=0 and p4_pe4_1[j]>=0 and p5_pe5_1[j]>=0 and p6_pe6_1[j]>=0 and p7_pe7_1[j]>=0 and p8_pe8_1[j]>=0 and p9_pe9_1[j]>=0 and p10_pe10_1[j]>=0 and p11_pe11_1[j]>=0 and p12_pe12_1[j]>=0:\n",
    "            reserve_j_1_1.append(j)\n",
    "        else:\n",
    "            reserve_j_1_2.append(j) \n",
    "    n1_1 = len(reserve_j_1_1)\n",
    "    n1_2 = len(reserve_j_1_2)\n",
    "    ratio1_1 = n1_1/n\n",
    "    ratio1_2 = n1_2/n\n",
    "    total1_1 = n1_1/total\n",
    "    total1_2 = n1_2/total\n",
    "    tb1_1 = x1[reserve_j_1_1].tolist()\n",
    "    E1_1 = y1[reserve_j_1_1].tolist()\n",
    "    tb1_2 = x1[reserve_j_1_2].tolist()\n",
    "    E1_2 = y1[reserve_j_1_2].tolist()\n",
    "        \n",
    "    if n1_1>0:\n",
    "        TB1_1_mean=np.mean(tb1_1)\n",
    "        E1_1_mean=np.mean(E1_1)\n",
    "        TB1_1_max=max(tb1_1)\n",
    "        E1_1_max=max(E1_1)\n",
    "        TB1_1_min=min(tb1_1)\n",
    "        E1_1_min=min(E1_1)\n",
    "    else:\n",
    "        TB1_1_mean=999999\n",
    "        E1_1_mean=999999\n",
    "        TB1_1_max=999999\n",
    "        E1_1_max=999999\n",
    "        TB1_1_min=999999\n",
    "        E1_1_min=999999\n",
    "    if n1_2>0:\n",
    "        TB1_2_mean=np.mean(tb1_2)\n",
    "        E1_2_mean=np.mean(E1_2)\n",
    "        TB1_2_max=max(tb1_2)\n",
    "        E1_2_max=max(E1_2)\n",
    "        TB1_2_min=min(tb1_2)\n",
    "        E1_2_min=min(E1_2)\n",
    "    else:\n",
    "        TB1_2_mean=999999\n",
    "        E1_2_mean=999999\n",
    "        TB1_2_max=999999\n",
    "        E1_2_max=999999\n",
    "        TB1_2_min=999999\n",
    "        E1_2_min=999999\n",
    "#计算第一区TB,E的最大值，最小值，均值，标准差，均值+标准差，均值-标准差 \n",
    "    if n1 > 0:\n",
    "        TB_1_max = max(tb1)\n",
    "        TB_1_min = min(tb1)\n",
    "        TB_1_mean = np.mean(tb1)\n",
    "        TB_1_std = np.std(tb1)\n",
    "        TB_1_mean_plus_std = TB_1_mean + TB_1_std\n",
    "        TB_1_mean_minus_std = TB_1_mean - TB_1_std\n",
    "        E_1_max = max(E1)\n",
    "        E_1_min = min(E1)\n",
    "        E_1_mean = np.mean(E1)\n",
    "        E_1_std = np.std(E1)\n",
    "        E_1_mean_plus_std = E_1_mean + E_1_std\n",
    "        E_1_mean_minus_std = E_1_mean - E_1_std\n",
    "    else:\n",
    "        E_1_mean=999999\n",
    "        E_1_std=999999\n",
    "        E_1_max=999999\n",
    "        E_1_min=999999\n",
    "        E_1_mean_plus_std=999999\n",
    "        E_1_mean_minus_std=999999\n",
    "        TB_1_mean=999999\n",
    "        TB_1_std=999999\n",
    "        TB_1_max=999999\n",
    "        TB_1_min=999999\n",
    "        TB_1_mean_plus_std=999999\n",
    "        TB_1_mean_minus_std=999999\n",
    "\n",
    "    tb2 = x[reserve_j_2].tolist()#转成列表\n",
    "    E2 = y[reserve_j_2].tolist()\n",
    "    n2 = len(reserve_j_2)\n",
    "    ratio2 = n2/n\n",
    "    total_2=n2/total\n",
    "#计算第二区TB,E的最大值，最小值，均值，标准差，均值+标准差，均值-标准差       \n",
    "    if n2 > 0:\n",
    "        TB_2_max = max(tb2)\n",
    "        TB_2_min = min(tb2)\n",
    "        TB_2_mean = np.mean(tb2)\n",
    "        TB_2_std = np.std(tb2)\n",
    "        TB_2_mean_plus_std = TB_2_mean + TB_2_std\n",
    "        TB_2_mean_minus_std = TB_2_mean - TB_2_std\n",
    "        E_2_max = max(E2)\n",
    "        E_2_min = min(E2)\n",
    "        E_2_mean = np.mean(E2)\n",
    "        E_2_std = np.std(E2)\n",
    "        E_2_mean_plus_std = E_2_mean + E_2_std\n",
    "        E_2_mean_minus_std = E_2_mean - E_2_std\n",
    "    else:\n",
    "        E_2_mean=999999\n",
    "        E_2_std=999999\n",
    "        E_2_max=999999\n",
    "        E_2_min=999999\n",
    "        E_2_mean_plus_std=999999\n",
    "        E_2_mean_minus_std=999999\n",
    "        TB_2_mean=999999\n",
    "        TB_2_std=999999\n",
    "        TB_2_max=999999\n",
    "        TB_2_min=999999\n",
    "        TB_2_mean_plus_std=999999\n",
    "        TB_2_mean_minus_std=999999 \n",
    "#     print('第二区：%d'%n2)\n",
    "    tb3 = x[reserve_j_3].tolist()#转成列表\n",
    "    E3 = y[reserve_j_3].tolist()\n",
    "    n3 = len(reserve_j_3)\n",
    "    ratio3 = n3/n\n",
    "    total_3=n3/total\n",
    "#计算第三区TB,E的最大值，最小值，均值，标准差，均值+标准差，均值-标准差    \n",
    "    if n3 > 0:\n",
    "        TB_3_max = max(tb3)\n",
    "        TB_3_min = min(tb3)\n",
    "        TB_3_mean = np.mean(tb3)\n",
    "        TB_3_std = np.std(tb3)\n",
    "        TB_3_mean_plus_std = TB_3_mean + TB_3_std\n",
    "        TB_3_mean_minus_std = TB_3_mean - TB_3_std\n",
    "        E_3_max = max(E3)\n",
    "        E_3_min = min(E3)\n",
    "        E_3_mean = np.mean(E3)\n",
    "        E_3_std = np.std(E3)\n",
    "        E_3_mean_plus_std = E_3_mean + E_3_std\n",
    "        E_3_mean_minus_std = E_3_mean - E_3_std\n",
    "    else:\n",
    "        E_3_mean=999999\n",
    "        E_3_std=999999\n",
    "        E_3_max=999999\n",
    "        E_3_min=999999\n",
    "        E_3_mean_plus_std=999999\n",
    "        E_3_mean_minus_std=999999\n",
    "        TB_3_mean=999999\n",
    "        TB_3_std=999999\n",
    "        TB_3_max=999999\n",
    "        TB_3_min=999999\n",
    "        TB_3_mean_plus_std=999999\n",
    "        TB_3_mean_minus_std=999999\n",
    "#     print('第三区：%d'%n3)\n",
    "    tb4 = x[reserve_j_4].tolist()#转成列表\n",
    "    E4 = y[reserve_j_4].tolist()\n",
    "    n4 = len(reserve_j_4)\n",
    "    ratio4 = n4/n\n",
    "    total_4=n4/total\n",
    "\n",
    "#计算第四区TB,AET,OOV的最大值，最小值，均值，标准差，均值+标准差，均值-标准差  \n",
    "    if n4 > 0:\n",
    "        TB_4_max = max(tb4)\n",
    "        TB_4_min = min(tb4)\n",
    "        TB_4_mean = np.mean(tb4)\n",
    "        TB_4_std = np.std(tb4)\n",
    "        TB_4_mean_plus_std = TB_4_mean + TB_4_std\n",
    "        TB_4_mean_minus_std = TB_4_mean - TB_4_std\n",
    "        E_4_max = max(E4)\n",
    "        E_4_min = min(E4)\n",
    "        E_4_mean = np.mean(E4)\n",
    "        E_4_std = np.std(E4)\n",
    "        E_4_mean_plus_std = E_4_mean + E_4_std\n",
    "        E_4_mean_minus_std = E_4_mean - E_4_std\n",
    "    else:\n",
    "        E_4_mean=999999\n",
    "        E_4_std=999999\n",
    "        E_4_max=999999\n",
    "        E_4_min=999999\n",
    "        E_4_mean_plus_std=999999\n",
    "        E_4_mean_minus_std=999999\n",
    "        TB_4_mean=999999\n",
    "        TB_4_std=999999\n",
    "        TB_4_max=999999\n",
    "        TB_4_min=999999\n",
    "        TB_4_mean_plus_std=999999\n",
    "        TB_4_mean_minus_std=999999\n",
    "\n",
    "    tb_234=tb2+tb3+tb4\n",
    "    E_234=E2+E3+E4\n",
    "    n_check=n1+n2+n3+n4\n",
    "    \n",
    "\n",
    "    all_value = {'n':n,'n_check':n_check,\n",
    "#                  '回归方程':\"E = %.2f *TB  + %.2f\" % (poly_val[1], poly_val[0]),'R2':R2,'P':P,\n",
    "#                 '拟合线斜率':poly_val[1],'拟合线截距':poly_val[0],\n",
    "#                  '95%置信上限截距':d_up,'95%置信下限截距':d_down,\n",
    "                'E_mean':E_mean,'E_std':E_std,'E_max':E_max,'E_min':E_min,'E_mean_plus_std':E_mean_plus_std,'E_mean_minus_std':E_mean_minus_std,\n",
    "                'TB_mean':TB_mean,'TB_std':TB_std,'TB_max':TB_max,'TB_min':TB_min,'TB_mean_plus_std':TB_mean_plus_std,'TB_mean_minus_std':TB_mean_minus_std,\n",
    "                'E_1_mean':E_1_mean,'E_1_std':E_1_std,'E_1_max':E_1_max,'E_1_min':E_1_min,'E_1_mean_plus_std':E_1_mean_plus_std,'E_1_mean_minus_std':E_1_mean_minus_std,\n",
    "                'TB_1_mean':TB_1_mean,'TB_1_std':TB_1_std,'TB_1_max':TB_1_max,'TB_1_min':TB_1_min,'TB_1_mean_plus_std':TB_1_mean_plus_std,'TB_1_mean_minus_std':TB_1_mean_minus_std,\n",
    "                'n1':n1,'ratio1':ratio1,\n",
    "                'E_2_mean':E_2_mean,'E_2_std':E_2_std,'E_2_max':E_2_max,'E_2_min':E_2_min,'E_2_mean_plus_std':E_2_mean_plus_std,'E_2_mean_minus_std':E_2_mean_minus_std,\n",
    "                'TB_2_mean':TB_2_mean,'TB_2_std':TB_2_std,'TB_2_max':TB_2_max,'TB_2_min':TB_2_min,'TB_2_mean_plus_std':TB_2_mean_plus_std,'TB_2_mean_minus_std':TB_2_mean_minus_std,\n",
    "                'n2':n2,'ratio2':ratio2,\n",
    "                'E_3_mean':E_3_mean,'E_3_std':E_3_std,'E_3_max':E_3_max,'E_3_min':E_3_min,'E_3_mean_plus_std':E_3_mean_plus_std,'E_3_mean_minus_std':E_3_mean_minus_std,\n",
    "                'TB_3_mean':TB_3_mean,'TB_3_std':TB_3_std,'TB_3_max':TB_3_max,'TB_3_min':TB_3_min,'TB_3_mean_plus_std':TB_3_mean_plus_std,'TB_3_mean_minus_std':TB_3_mean_minus_std,\n",
    "                'n3':n3,'ratio3':ratio3,\n",
    "                'E_4_mean':E_4_mean,'E_4_std':E_4_std,'E_4_max':E_4_max,'E_4_min':E_4_min,'E_4_mean_plus_std':E_4_mean_plus_std,'E_4_mean_minus_std':E_4_mean_minus_std,\n",
    "                'TB_4_mean':TB_4_mean,'TB_4_std':TB_4_std,'TB_4_max':TB_4_max,'TB_4_min':TB_4_min,'TB_4_mean_plus_std':TB_4_mean_plus_std,'TB_4_mean_minus_std':TB_4_mean_minus_std,\n",
    "                'n4':n4,'ratio4':ratio4,\n",
    "                'tb1':tb1,'tb2':tb2,'tb3':tb3,'tb4':tb4,\n",
    "                 'E1':E1,'E2':E2,'E3':E3,'E4':E4,'tb_234':tb_234,'E_234':E_234,\n",
    "                'ratio1_1':ratio1_1,'ratio1_2':ratio1_2,\n",
    "                 'TB1_1_mean':TB1_1_mean,'TB1_2_mean':TB1_2_mean,'E1_1_mean':E1_1_mean,'E1_2_mean':E1_2_mean,\n",
    "                 'TB1_1_max':TB1_1_max,'TB1_2_max':TB1_2_max,'E1_1_max':E1_1_max,'E1_2_max':E1_2_max,\n",
    "                 'TB1_1_min':TB1_1_min,'TB1_2_min':TB1_2_min,'E1_1_min':E1_1_min,'E1_2_min':E1_2_min,\n",
    "                'total1_1': total1_1,'total1_2': total1_2,'total_2': total_2,'total_3': total_3,\n",
    "                'p_mean':p_mean,'p_std':p_std,'p_max':p_max,'p_min':p_min,\n",
    "                'pe_mean':pe_mean,'pe_std':pe_std,'pe_max':pe_max,'pe_min':pe_min,\n",
    "                'DEM_mean':DEM_mean,'DEM_std':DEM_std,'DEM_max':DEM_max,'DEM_min':DEM_min,\n",
    "                'tp_year_mean':tp_year_mean,'tp_year_std':tp_year_std,'tp_year_max':tp_year_max,'tp_year_min':tp_year_min}\n",
    "    return all_value"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "#画左上角条形折线图函数\n",
    "def barline1(all_value0,all_value1,fig):\n",
    "#画柱形图  \n",
    "    axins = fig.add_axes([0.15,0.71,0.25,0.165])\n",
    "    plt.rcParams['font.sans-serif'] = ['SimHei']\n",
    "    plt.rcParams['axes.unicode_minus'] = False \n",
    "    x=[ 0.5, 1.1 ,1.7,  2.3]\n",
    "    height=[all_value1['total1_1']*100,all_value1['total1_2']*100,all_value1['total_2']*100,all_value1['total_3']*100]\n",
    "#     x1=[1]\n",
    "#     x2=[1.6]\n",
    "#     x3=[2.2]\n",
    "#     x4=[2.8]\n",
    "    x1=[0.5]\n",
    "    x2=[1.1]\n",
    "    x3=[1.7]\n",
    "    x4=[2.3]\n",
    "    zone1=['Ⅰ','Ⅱ','Ⅲ','Ⅳ']\n",
    "    patches = axins.bar(x,height, width= 0.2,tick_label=zone1,facecolor='w',edgecolor='k')\n",
    "    axins.set_ylim(0,100)\n",
    "    axins.set_xlim(0,3)\n",
    "    plt.xticks(fontproperties=font_set1_1)\n",
    "    for rect in patches:\n",
    "        height = rect.get_height()\n",
    "        if height>0:\n",
    "            axins.text(rect.get_x() + rect.get_width() / 2, height, str('%.2f'%height)+'%', ha='center', va='bottom',fontproperties =font_set3)\n",
    "#TB轴    \n",
    "    axins1=axins.twinx()\n",
    "    tb1_mean=[all_value1['TB1_1_mean']]\n",
    "    tb2_mean=[all_value1['TB1_2_mean']]\n",
    "    tb3_mean=[all_value1['TB_2_mean']]\n",
    "    tb4_mean=[all_value1['TB_3_mean']]\n",
    "    tb1_max=[all_value1['TB1_1_max']]\n",
    "    tb2_max=[all_value1['TB1_2_max']]\n",
    "    tb3_max=[all_value1['TB_2_max']]\n",
    "    tb4_max=[all_value1['TB_3_max']]\n",
    "    tb1_min=[all_value1['TB1_1_min']]\n",
    "    tb2_min=[all_value1['TB1_2_min']]\n",
    "    tb3_min=[all_value1['TB_2_min']]\n",
    "    tb4_min=[all_value1['TB_3_min']]\n",
    "    y=[panduan(tb1_mean),panduan(tb2_mean),panduan(tb3_mean),panduan(tb4_mean)]\n",
    "    y=tuli(y)\n",
    "    plotsca_tb(axins1,tb1_mean,x1,y[0])\n",
    "    plotsca_tb(axins1,tb1_max,x1,0)\n",
    "    plotsca_tb(axins1,tb1_min,x1,0)\n",
    "    plotsca_tb(axins1,tb2_mean,x2,y[1])\n",
    "    plotsca_tb(axins1,tb2_max,x2,0)\n",
    "    plotsca_tb(axins1,tb2_min,x2,0)\n",
    "    plotsca_tb(axins1,tb3_mean,x3,y[2])\n",
    "    plotsca_tb(axins1,tb3_max,x3,0)\n",
    "    plotsca_tb(axins1,tb3_min,x3,0)\n",
    "    plotsca_tb(axins1,tb4_mean,x4,y[3])\n",
    "    plotsca_tb(axins1,tb4_max,x4,0)\n",
    "    plotsca_tb(axins1,tb4_min,x4,0) \n",
    "    axins1.set_ylabel('TB (℃)',fontproperties =font_set1)\n",
    "    \n",
    "    TB_min=[all_value1['TB1_1_min'],\n",
    "            all_value1['TB1_2_min'],\n",
    "            all_value1['TB_2_min'],\n",
    "            all_value1['TB_3_min']] \n",
    "    axins1_min=[]\n",
    "    for i in range(0,len(TB_min)):\n",
    "        if TB_min[i]!=999999:\n",
    "            axins1_min.append(TB_min[i])\n",
    "    axins1_min=min(axins1_min)    \n",
    "    TB_max=[all_value1['TB1_1_max'],\n",
    "            all_value1['TB1_2_max'],\n",
    "            all_value1['TB_2_max'],\n",
    "            all_value1['TB_3_max']]\n",
    "    axins1_max=[]\n",
    "    for i in range(0,len(TB_max)):\n",
    "        if TB_max[i]!=999999:\n",
    "            axins1_max.append(TB_max[i])\n",
    "    axins1_max=max(axins1_max)\n",
    "\n",
    "    \n",
    "    ymajorLocator = MultipleLocator(5)\n",
    "    ymajorFormatter = FormatStrFormatter('%d')\n",
    "    axins1.yaxis.set_major_locator(ymajorLocator)\n",
    "    axins1.yaxis.set_major_formatter(ymajorFormatter)\n",
    "    axins1.set_ylim(0,30)        \n",
    "#画温度带\n",
    "    xzone=[2.61,2.77,2.77,2.77,2.77,2.77,2.85]\n",
    "    yzone=[0.2,1.7,4,7.3,11.3,17,22.5]\n",
    "    zone=['高山极地带', '苔原带', '寒温带', '中温带', '暖温带', '亚热带', '热带']\n",
    "    line=[0,1.5,3,6,10,14,22,30]\n",
    "    t1={}\n",
    "    t2={}\n",
    "    for i in range(len(line)):\n",
    "        if line[i]<=axins1_min<line[i+1]:\n",
    "            t1=i\n",
    "    for i in range(len(line)):\n",
    "        if axins1_max<=line[i]:\n",
    "            t2=i\n",
    "            break\n",
    "    for i in range(t1,(t2+1)):\n",
    "        axins1.plot([line[i]]*16,\"--\",linewidth=0.5,color='r',alpha=0.7)\n",
    "    for i in range(t1,t2):\n",
    "        axins1.text(xzone[i],yzone[i],zone[i], fontproperties =font_set4)\n",
    "        \n",
    "    axins1.legend(loc=\"upper right\",frameon=False,prop=font_set1)\n",
    "\n",
    "#E轴    \n",
    "    axins2=axins.twinx()\n",
    "    e1_mean=[all_value1['E1_1_mean']]\n",
    "    e2_mean=[all_value1['E1_2_mean']]\n",
    "    e3_mean=[all_value1['E_2_mean']]\n",
    "    e4_mean=[all_value1['E_3_mean']]\n",
    "    e1_max=[all_value1['E1_1_max']]\n",
    "    e2_max=[all_value1['E1_2_max']]\n",
    "    e3_max=[all_value1['E_2_max']]\n",
    "    e4_max=[all_value1['E_3_max']]\n",
    "    e1_min=[all_value1['E1_1_min']]\n",
    "    e2_min=[all_value1['E1_2_min']]\n",
    "    e3_min=[all_value1['E_2_min']]\n",
    "    e4_min=[all_value1['E_3_min']]\n",
    "    y=[panduan(e1_mean),panduan(e2_mean),panduan(e3_mean),panduan(e4_mean)]\n",
    "    y=tuli(y)\n",
    "    plotsca_E(axins2,e1_mean,x1,y[0])\n",
    "    plotsca_E(axins2,e1_max,x1,0)\n",
    "    plotsca_E(axins2,e1_min,x1,0)\n",
    "    plotsca_E(axins2,e2_mean,x2,y[1])\n",
    "    plotsca_E(axins2,e2_max,x2,0)\n",
    "    plotsca_E(axins2,e2_min,x2,0)\n",
    "    plotsca_E(axins2,e3_mean,x3,y[2])\n",
    "    plotsca_E(axins2,e3_max,x3,0)\n",
    "    plotsca_E(axins2,e3_min,x3,0)\n",
    "    plotsca_E(axins2,e4_mean,x4,y[3])\n",
    "    plotsca_E(axins2,e4_max,x4,0)\n",
    "    plotsca_E(axins2,e4_min,x4,0)\n",
    "    axins2.set_ylabel('E',fontproperties =font_set1)\n",
    "    \n",
    "    E_min=[all_value1['E1_1_min'],\n",
    "            all_value1['E1_2_min'],\n",
    "            all_value1['E_2_min'],\n",
    "            all_value1['E_3_min']]\n",
    "    axins2_min=[]\n",
    "    for i in range(0,len(E_min)):\n",
    "        if E_min[i]!=999999:\n",
    "            axins2_min.append(E_min[i])\n",
    "    axins2_min=min(axins2_min)    \n",
    "    E_max=[all_value1['E1_1_max'],\n",
    "            all_value1['E1_2_max'],\n",
    "            all_value1['E_2_max'],\n",
    "            all_value1['E_3_max']]\n",
    "    axins2_max=[]\n",
    "    for i in range(0,len(E_max)):\n",
    "        if E_max[i]!=999999:\n",
    "            axins2_max.append(E_max[i])\n",
    "    axins2_max=max(axins2_max)\n",
    " #设置E轴的刻度 \n",
    "    ax_min=math.ceil(axins2_min)-5\n",
    "    ax_max=math.ceil(axins2_max)+5\n",
    "    step=math.ceil((ax_max-ax_min)/5)\n",
    "    l=math.ceil(ax_max/step)\n",
    "    axins2_ymax=l*(step)\n",
    "    axins2_ymin=axins2_ymax-6*(step)\n",
    "    axins2.set_ylim(axins2_ymin,axins2_ymax)\n",
    "    ymajorLocator = MultipleLocator(step)\n",
    "    ymajorFormatter = FormatStrFormatter('%d')\n",
    "    axins2.yaxis.set_major_locator(ymajorLocator)\n",
    "    axins2.yaxis.set_major_formatter(ymajorFormatter)\n",
    "    axins2.spines[\"right\"].set_position((\"axes\", 1.11))\n",
    "    axins2.legend(bbox_to_anchor=(0.985,0.93),frameon=False,prop=font_set1)\n",
    "    return axins,axins1,axins2    \n",
    "\n",
    "import os #读取某个文件夹下的全部csv，其中os.path.splitext()函数将路径拆分为文件名+扩展名\n",
    "def file_name(file_dir):  \n",
    "    L=[]\n",
    "    name=[]\n",
    "    for root, dirs, files in os.walk(file_dir): \n",
    "        for file in files: \n",
    "            if os.path.splitext(file)[1] == '.csv': \n",
    "                L.append(os.path.join(root, file))\n",
    "                name.append(file)\n",
    "    return L,name \n",
    "\n",
    "#目前只支持寒温带落叶针叶林区域\n",
    "import xlrd\n",
    "import sqlite3\n",
    "def get_bianhao(a):\n",
    "    a=\"'\"+a+\"'\"\n",
    "    conn=sqlite3.connect('mrsoft.db')\n",
    "    cursor=conn.cursor()\n",
    "    cursor.execute('select name from zhibei where bh='+a)\n",
    "    result1=cursor.fetchone()\n",
    "    cursor.close()\n",
    "    conn.close()\n",
    "    return result1[0]\n",
    "\n",
    "def judge_xy(x,y):\n",
    "    a=1\n",
    "    for j,x[j] in enumerate(x):\n",
    "        if (0<=x[j]<=4.8 or 7<x[j]<=13) and y[j]>=400:\n",
    "            a=0\n",
    "            break\n",
    "        elif  4.8<x[j]<=7 and y[j]>=360:\n",
    "            a=0\n",
    "            break\n",
    "        elif  x[j]>13 and y[j]>=690:\n",
    "            a=0\n",
    "            break\n",
    "    return a"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "# 构建回归模型图示\n",
    "def figure_drawing(x,y,zz,alpha,fig,ax,**kwargs):\n",
    "    all_value = data_process(x,y,alpha)\n",
    "#     plt.rcParams['ytick.direction'] = 'out'\n",
    "#     fig, ax = plt.subplots(figsize = (12,8))\n",
    "#     ax.xaxis.set_ticks_position('bottom')\n",
    "#     ax.spines['bottom'].set_position(('data', 0))\n",
    "#     ax.yaxis.set_ticks_position('left')\n",
    "#     ax.spines['left'].set_position(('data', 0))\n",
    "#     ax.spines['right'].set_color('none')\n",
    "#     ax.spines['top'].set_color('none')\n",
    "    \n",
    "    fig.patch.set_facecolor('white')\n",
    "    ax.xaxis.set_ticks_position('bottom')\n",
    "    ax.spines['bottom'].set_position(('data', 0))\n",
    "    ax.yaxis.set_ticks_position('left')\n",
    "    ax.spines['left'].set_position(('data', 0))\n",
    "    ax.spines['right'].set_color('none')\n",
    "    ax.spines['top'].set_color('none')\n",
    "    \n",
    "    ax.grid(ls='--',linewidth=0.4)\n",
    "    \n",
    "\n",
    "    ylimit_down = min(y)\n",
    "    ylimit_up = max(y)\n",
    "    \n",
    "#分区回归\n",
    "#第一区\n",
    "    x1 = all_value['tb1']\n",
    "    y1 = all_value['E1']  \n",
    "#     if all_value['n1']==0:\n",
    "#         print('第一区为空')\n",
    "#第二区\n",
    "    x2 =all_value['tb2']\n",
    "    y2 =all_value['E2'] \n",
    "#第三区\n",
    "    x3 =all_value['tb3']\n",
    "    y3 =all_value['E3']\n",
    "    \n",
    "    x4 =all_value['tb4']\n",
    "    y4 =all_value['E4']\n",
    "#二三区一起做回归\n",
    "    x234=x2+x3+x4\n",
    "    y234=y2+y3+y4\n",
    "#分类\n",
    "    if zz==1:\n",
    "        xy=np.vstack((x,y))\n",
    "        xy=np.stack(xy,axis=1)\n",
    "        xy=np.array(xy)\n",
    "    \n",
    "        xy1=[]\n",
    "    elif zz==2:\n",
    "        xy=np.vstack((x1,y1))\n",
    "        xy=np.stack(xy,axis=1)\n",
    "        xy=np.array(xy)\n",
    "    \n",
    "        xy1=np.vstack((x234,y234))\n",
    "        xy1=np.stack(xy1,axis=1)\n",
    "        xy1=np.array(xy1)\n",
    "    elif zz=='1':\n",
    "        global x_1,y_1,x_2,y_2\n",
    "        xy=[]\n",
    "        xy1=[]\n",
    "        x_1=float(input('请输入分界点1的横坐标'))\n",
    "        y_1=float(input('请输入分界点1的纵坐标'))\n",
    "        x_2=float(input('请输入分界点2的横坐标'))\n",
    "        y_2=float(input('请输入分界点2的纵坐标'))\n",
    "        k1=(y_1-y_2)/(x_1-x_2)\n",
    "        b1=y_1-k1*x_1\n",
    "#         xxx1=np.linspace(0,math.ceil(max(x))+6, 1000000)\n",
    "#         yyy1=k1*xxx1+b1\n",
    "#         poly_text0= \"分段界限:\"+\"$E = %.2f *TB  + %.2f$\" % (k1, b1)\n",
    "#         plt.plot( xxx1, yyy1, '-',color='k',label=poly_text0, linewidth=0.5)\n",
    "        for i in range(len(x)):\n",
    "            if y[i]>k1*x[i]+b1 :\n",
    "                xy.append([x[i],y[i]])\n",
    "            elif y[i]<=k1*x[i]+b1:\n",
    "                xy1.append([x[i],y[i]])\n",
    "        \n",
    "        xy=np.array(xy)\n",
    "        xy1=np.array(xy1)\n",
    "                \n",
    "    \n",
    "    xy2=[]\n",
    "    xy3=[]\n",
    "    xy4=[]\n",
    "\n",
    "    xy2=np.array(xy2)\n",
    "    xy3=np.array(xy3)\n",
    "    xy4=np.array(xy4)\n",
    "    A = ['1','2','3','4','5']\n",
    "    B = [xy,xy1,xy2,xy3,xy4]\n",
    "    z=dict(zip(A,B))\n",
    "    spotValue=['g','g','y','steelblue','sandybrown']\n",
    "    lineValue=['darkred','darkred','gold','deepskyblue','orangered']\n",
    "    qunluo=['类型3','类型3','类型3','类型4','类型5']\n",
    "    \n",
    "    diyu=''\n",
    "    spot_color=int(str5_4)\n",
    "    spot_color1=int(str5_2_1)\n",
    "    \n",
    "    if spot_color==1:\n",
    "        spotValue[0]=spotValue[1]='r'\n",
    "        qunluo[0]=qunluo[1]=diyu+'类型1'\n",
    "    elif spot_color==2:\n",
    "        spotValue[0]=spotValue[1]='darkorchid'\n",
    "        qunluo[0]=qunluo[1]=diyu+'类型2'\n",
    "    elif spot_color==3:\n",
    "        spotValue[0]=spotValue[1]='g'\n",
    "        qunluo[0]=qunluo[1]=diyu+'类型3'\n",
    "    elif spot_color==4:\n",
    "        spotValue[0]=spotValue[1]='b'\n",
    "        qunluo[0]=qunluo[1]=diyu+'类型4'\n",
    "    elif spot_color==5:\n",
    "        spotValue[0]=spotValue[1]='fuchsia'\n",
    "        qunluo[0]=qunluo[1]=diyu+'类型5'\n",
    "    elif spot_color==6:\n",
    "        spotValue[0]=spotValue[1]='limegreen'\n",
    "        qunluo[0]=qunluo[1]=diyu+'类型6'\n",
    "    elif spot_color==7:\n",
    "        spotValue[0]=spotValue[1]='lightseagreen'\n",
    "        qunluo[0]=qunluo[1]=diyu+'类型7'\n",
    "    elif spot_color==8:\n",
    "        spotValue[0]=spotValue[1]='chocolate'\n",
    "        qunluo[0]=qunluo[1]=diyu+'类型8'\n",
    "    elif spot_color==9:\n",
    "        spotValue[0]=spotValue[1]='deepskyblue'\n",
    "        qunluo[0]=qunluo[1]=diyu+'类型9'\n",
    "    elif spot_color==10:\n",
    "        spotValue[0]=spotValue[1]='y'\n",
    "        qunluo[0]=qunluo[1]=diyu+'类型10'\n",
    "    elif spot_color==11:\n",
    "        spotValue[0]=spotValue[1]='#990033'\n",
    "        qunluo[0]=qunluo[1]=diyu+'类型11'\n",
    "    elif spot_color==12:\n",
    "        spotValue[0]=spotValue[1]='#FF9966'\n",
    "        qunluo[0]=qunluo[1]=diyu+'类型12'\n",
    "    elif spot_color==13:\n",
    "        spotValue[0]=spotValue[1]='#996699'\n",
    "        qunluo[0]=qunluo[1]=diyu+'类型13'\n",
    "    elif spot_color==14:\n",
    "        spotValue[0]=spotValue[1]='#FF99CC'\n",
    "        qunluo[0]=qunluo[1]=diyu+'类型14'\n",
    "    elif spot_color==15:\n",
    "        spotValue[0]=spotValue[1]='#999900'\n",
    "        qunluo[0]=qunluo[1]=diyu+'类型15'\n",
    "    elif spot_color==16:\n",
    "        spotValue[0]=spotValue[1]='#50616d'\n",
    "        qunluo[0]=qunluo[1]=diyu+'类型16' \n",
    "    elif spot_color==17:\n",
    "        spotValue[0]=spotValue[1]='maroon'\n",
    "        qunluo[0]=qunluo[1]=diyu+'类型17'\n",
    "    elif spot_color==18:\n",
    "        spotValue[0]=spotValue[1]='bisque'\n",
    "        qunluo[0]=qunluo[1]=diyu+'类型18'\n",
    "    elif spot_color==19:\n",
    "        spotValue[0]=spotValue[1]='darkblue'\n",
    "        qunluo[0]=qunluo[1]=diyu+'类型19'\n",
    "    elif spot_color1==0 and spot_color ==0 :\n",
    "        spotValue[0]=spotValue[1]='y'\n",
    "        qunluo[0]=qunluo[1]='温度交错带'   \n",
    "    elif spot_color1==1 and spot_color ==0 :\n",
    "        spotValue[0]=spotValue[1]='darkorchid'\n",
    "        qunluo[0]=qunluo[1]='高山极地带'     \n",
    "    elif spot_color1==2 and spot_color ==0 :\n",
    "        spotValue[0]=spotValue[1]='fuchsia'\n",
    "        qunluo[0]=qunluo[1]='苔原带'\n",
    "    elif spot_color1==3 and spot_color ==0 :\n",
    "        spotValue[0]=spotValue[1]='b'\n",
    "        qunluo[0]=qunluo[1]='寒温带' \n",
    "    elif spot_color1==4 and spot_color ==0 :\n",
    "        spotValue[0]=spotValue[1]='mediumaquamarine'\n",
    "        qunluo[0]=qunluo[1]='中温带'     \n",
    "    elif spot_color1==5 and spot_color ==0 :\n",
    "        spotValue[0]=spotValue[1]='limegreen'\n",
    "        qunluo[0]=qunluo[1]='暖温带'\n",
    "    elif spot_color1==6 and spot_color ==0 :\n",
    "        spotValue[0]=spotValue[1]='darkorange'\n",
    "        qunluo[0]=qunluo[1]='亚热带' \n",
    "    elif spot_color1==7 and spot_color ==0 :\n",
    "        spotValue[0]=spotValue[1]='r'\n",
    "        qunluo[0]=qunluo[1]='热带' \n",
    "    \n",
    "    \n",
    "    if len(xy)==0:\n",
    "        j=1\n",
    "    else:\n",
    "        j=0\n",
    "    \n",
    "    regression=[]\n",
    "    for i in range(0,2):       \n",
    "        coo=[]\n",
    "        coo=z[A[i]]\n",
    "        if   0<len(coo)<=2:\n",
    "            if i==j:\n",
    "                ax.scatter(coo[:,0], coo[:,1], s=15,color=spotValue[i%len(spotValue)],label=qunluo[i%len(qunluo)])\n",
    "            else:\n",
    "                ax.scatter(coo[:,0], coo[:,1], s=15,color=spotValue[i%len(spotValue)])\n",
    "            regression.append(['/','/','/'])\n",
    "        elif len(coo)>2:\n",
    "            poly_val,test_val, process_val = polyfit_one(coo[:,0], coo[:,1],alpha)\n",
    "            if poly_val[0]==999999:\n",
    "                if len(coo)<=100:\n",
    "                    if i==j:\n",
    "                        ax.scatter(coo[:,0], coo[:,1], s=15,color=spotValue[i%len(spotValue)],label=qunluo[i%len(qunluo)])\n",
    "                    else:\n",
    "                        ax.scatter(coo[:,0], coo[:,1], s=15,color=spotValue[i%len(spotValue)])   \n",
    "                else:\n",
    "                    if i==j:\n",
    "                        ax.scatter(coo[:,0], coo[:,1], s=10,color=spotValue[i%len(spotValue)],label=qunluo[i%len(qunluo)])\n",
    "                    else:\n",
    "                        ax.scatter(coo[:,0], coo[:,1], s=10,color=spotValue[i%len(spotValue)])\n",
    "            elif poly_val[0]==99999999:\n",
    "                    poly_text1 = \"$TB = %.2f$\" % (poly_val[1])\n",
    "                    X_test = np.ones(1000000)*poly_val[1]\n",
    "                    Y_test = np.linspace(-60,60, 1000000)\n",
    "                    plt.plot( X_test, Y_test, '-',color=lineValue[i%len(lineValue)],label=poly_text1, linewidth=1)\n",
    "                    if len(coo)<=100:\n",
    "                        if i==j:\n",
    "                            ax.scatter(coo[:,0], coo[:,1], s=15,color=spotValue[i%len(spotValue)],label=qunluo[i%len(qunluo)])\n",
    "                        else:\n",
    "                            ax.scatter(coo[:,0], coo[:,1], s=15,color=spotValue[i%len(spotValue)])   \n",
    "                    else:\n",
    "                        if i==j:\n",
    "                            ax.scatter(coo[:,0], coo[:,1], s=10,color=spotValue[i%len(spotValue)],label=qunluo[i%len(qunluo)])\n",
    "                        else:\n",
    "                            ax.scatter(coo[:,0], coo[:,1], s=10,color=spotValue[i%len(spotValue)])\n",
    "            else:\n",
    "                if 0 <= poly_val[0]< 99999999:\n",
    "                    poly_text1 = \"$E = %.2f *TB  + %.2f$（$R^2 = %.2f$）\" % (poly_val[1], poly_val[0],test_val['R2'])#加$会使字体倾斜加粗\n",
    "                else:\n",
    "                    poly_text1 = \"$E = %.2f *TB  + %.2f$（$R^2 = %.2f$）\" % (poly_val[1], poly_val[0],test_val['R2'])\n",
    "        \n",
    "                if len(coo)<=100:\n",
    "                    if i==j:\n",
    "                        ax.scatter(coo[:,0], coo[:,1], s=15,color=spotValue[i%len(spotValue)],label=qunluo[i%len(qunluo)])\n",
    "                    else:\n",
    "                        ax.scatter(coo[:,0], coo[:,1], s=15,color=spotValue[i%len(spotValue)])   \n",
    "                else:\n",
    "                    if i==j:\n",
    "                        ax.scatter(coo[:,0], coo[:,1], s=10,color=spotValue[i%len(spotValue)],label=qunluo[i%len(qunluo)])\n",
    "                    else:\n",
    "                        ax.scatter(coo[:,0], coo[:,1], s=10,color=spotValue[i%len(spotValue)])\n",
    "                X_test = np.linspace(0,math.ceil(max(x))+6, 1000000)\n",
    "                Y_test = X_test* poly_val[1]+poly_val[0]\n",
    "                if zz == '1' and i==0:\n",
    "                    poly_text1=poly_text1+\"第一段\"\n",
    "                elif zz == '1' and i==1:\n",
    "                    poly_text1=poly_text1+\"第二段\"\n",
    "                \n",
    "                plt.plot( X_test, Y_test, '-',color=lineValue[i%len(lineValue)],label=poly_text1, linewidth=1)\n",
    "\n",
    "            regression.append([test_val['R2'],test_val['Pvalue'],poly_text1])\n",
    "    \n",
    "    \n",
    "    poly_text2 = '分区界限'\n",
    "    ax.plot(np.linspace(0, 30, 1000000), 5.893*1.8099*np.linspace(0, 30, 1000000), '--k', label=poly_text2)\n",
    "    ax.plot(np.linspace(0, 30, 1000000), -5.893*1.8099*np.linspace(0, 30, 1000000), '--k')\n",
    "    plt.axhline(0, color='k')#第四区线，p=1/2pe\n",
    "    \n",
    "    poly_text3='中心点位置'\n",
    "#     ax.scatter(all_value['TB_mean'],all_value['E_mean'],s=30,c='r',marker = 'o',label=poly_text3)  \n",
    "    \n",
    "    xlabel = 'TB (℃)'\n",
    "    ylabel = 'E'\n",
    "    ax.set_xlabel(xlabel,fontproperties =font_set)\n",
    "    ax.set_ylabel(ylabel,fontproperties =font_set)\n",
    "    \n",
    "   \n",
    "    judgexy=judge_xy(x,y)\n",
    "    xmajorLocator = MultipleLocator(1)\n",
    "    xmajorFormatter = FormatStrFormatter('%d')\n",
    "    ax.set_xlim(0,30)\n",
    "    if judgexy == 0:\n",
    "        ymajorLocator = MultipleLocator(100)\n",
    "        ax.set_ylim(-900,1500)\n",
    "        text_yvalue1=870\n",
    "        text_yvalue2=840\n",
    "    else:\n",
    "        ymajorLocator = MultipleLocator(50)\n",
    "        ax.set_ylim(-500,700)\n",
    "        text_yvalue1=390\n",
    "        text_yvalue2=370\n",
    "    ymajorFormatter = FormatStrFormatter('%1.1f')\n",
    "    ax.xaxis.set_major_locator(xmajorLocator)\n",
    "    ax.xaxis.set_major_formatter(xmajorFormatter)\n",
    "    ax.yaxis.set_major_locator(ymajorLocator)\n",
    "    ax.yaxis.set_major_formatter(ymajorFormatter)\n",
    "    \n",
    "\n",
    "    \n",
    "   \n",
    "    \n",
    "        \n",
    "    plt.text(29,350,'Ⅰ,Ⅱ', fontproperties =font_set)\n",
    "    plt.text(29.3,110,'Ⅲ', fontproperties =font_set)\n",
    "    plt.text(29.3,-190,'Ⅳ', fontproperties =font_set)\n",
    "\n",
    "    \n",
    "    \n",
    "    title = kwargs['title']\n",
    "    ax.set_title(title,fontproperties =font_set)\n",
    "#     plt.setp(ax.xaxis.get_majorticklabels(), rotation=-20)#坐标系数字的倾斜程度\n",
    "    \n",
    "    legend = ax.legend(loc=\"lower left\",prop=font_set1)\n",
    "    legend_f = legend.get_frame()\n",
    "    legend_f.set_facecolor(\"white\")\n",
    "\n",
    "#左上角画条形折线图\n",
    "    all_value0=data_process(np.array(x),np.array(y),alpha)\n",
    "    all_value1=data_process(np.array(x),np.array(y),alpha)\n",
    "    \n",
    "    if spot_color==0 and (spot_color1==0 or spot_color1 ==1):\n",
    "        plt.text(4.6,text_yvalue1,qunluo[0]+'('+str('%.2f'%(len(x)/total*100))+'%)', fontproperties =font_set1)\n",
    "    else:\n",
    "        plt.text(4.8,text_yvalue1,qunluo[0]+'('+str('%.2f'%(len(x)/total*100))+'%)', fontproperties =font_set1)\n",
    "    plt.text(4.8,text_yvalue2,'('+str('%.2f'%all_value1['TB_mean'])+','+str('%.2f'%all_value1['E_mean'])+')',fontproperties =font_set1)\n",
    "\n",
    "#         plt.text(4.8,390,qunluo[0]+'('+str('%.2f'%(len(x)/total*100))+'%)', fontproperties =font_set1)\n",
    "#         plt.text(4.8,370,'('+str('%.2f'%all_value1['TB_mean'])+','+str('%.2f'%all_value1['E_mean'])+')',fontproperties =font_set1)    \n",
    "    barline1(all_value0,all_value1,fig)  \n",
    "    legend = ax.legend(loc=\"lower left\",prop=font_set1)\n",
    "    legend_f = legend.get_frame()\n",
    "    legend_f.set_facecolor(\"white\")\n",
    "    return figure_drawing,regression\n",
    "\n",
    "def judge_p(p):\n",
    "    try:\n",
    "        if p>0.05:\n",
    "            Pvalue='P>0.05'\n",
    "        elif 0.001<p<=0.05:\n",
    "            Pvalue='0.001<P<=0.05'\n",
    "        elif p<=0.001:\n",
    "            Pvalue='P<=0.001'\n",
    "    except TypeError:\n",
    "        Pvalue=p\n",
    "    return Pvalue"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "\n",
      "当前csv:1.42.0.1.csv\n",
      "value值和data数据内不一致\n",
      "总样本点数：60229\n",
      "分区后的总样本点数：142\n",
      "\n",
      "当前csv:1.42.0.10.csv\n",
      "value值和data数据内不一致\n",
      "总样本点数：60229\n",
      "分区后的总样本点数：6\n",
      "\n",
      "当前csv:1.42.0.11.csv\n",
      "value值和data数据内不一致\n",
      "总样本点数：60229\n",
      "分区后的总样本点数：12\n",
      "\n",
      "当前csv:1.42.0.2.csv\n",
      "value值和data数据内不一致\n",
      "总样本点数：60229\n",
      "分区后的总样本点数：32\n",
      "\n",
      "当前csv:1.42.0.3.csv\n",
      "value值和data数据内不一致\n",
      "总样本点数：60229\n",
      "分区后的总样本点数：33\n",
      "\n",
      "当前csv:1.42.0.4.csv\n",
      "value值和data数据内不一致\n",
      "总样本点数：60229\n",
      "分区后的总样本点数：18\n",
      "\n",
      "当前csv:1.42.0.5.csv\n",
      "value值和data数据内不一致\n",
      "总样本点数：60229\n",
      "分区后的总样本点数：16\n",
      "\n",
      "当前csv:1.42.0.6.csv\n",
      "value值和data数据内不一致\n",
      "总样本点数：60229\n",
      "分区后的总样本点数：37\n",
      "\n",
      "当前csv:1.42.0.7.csv\n",
      "value值和data数据内不一致\n",
      "总样本点数：60229\n",
      "分区后的总样本点数：34\n",
      "\n",
      "当前csv:1.42.0.8.csv\n",
      "value值和data数据内不一致\n",
      "总样本点数：60229\n",
      "分区后的总样本点数：20\n",
      "\n",
      "当前csv:1.42.0.9.csv\n",
      "value值和data数据内不一致\n",
      "总样本点数：60229\n",
      "分区后的总样本点数：32\n",
      "\n",
      "各csv点数之和与该群系总点数不相等,请检查:\n",
      "1.该群系的所有csv是否同时跑了\n",
      "2.是否有漏点情况\n",
      "\n",
      "开始生成信息统计csv\n",
      "--------分割线--------\n",
      "write down\n"
     ]
    }
   ],
   "source": [
    "# coding: utf-8\n",
    "\n",
    "#就改这俩就行了\n",
    "List=['260_岗松灌丛_岗松灌丛_216']\n",
    "csvpath =r'E:\\tutu\\cut'#运行csv所在的文件夹，该程序运行的是该文件夹下的所有的csv文件\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "\n",
    "TSL='0'\n",
    "headers=['name','value','说明书名字','说明书群系编号','总样本点数','分区后总样本点数','温度带','区域','小地域','类型',\n",
    "         '总体回归方程','R方','P值','P值范围',\n",
    "         '分类型回归方程1','R方','P值','P值范围',\n",
    "         '分类型回归方程2','R方','P值','P值范围',\n",
    "        'TB_max','TB_min','TB_mean','TB_std',\n",
    "        'E_max','E_min','E_mean','E_std',\n",
    "        'p_max','p_min','p_mean','p_std',\n",
    "        'pe_max','pe_min','pe_mean','pe_std',\n",
    "        'dem_max','dem_min','dem_mean','dem_std',\n",
    "        'tp_year_max','tp_year_min','tp_year_mean','tp_year_std']\n",
    "rows=[]\n",
    "\n",
    "csv_number=0\n",
    "for i in List:\n",
    "    str1=i.split('_')[0]#value\n",
    "    str2=i.split('_')[1]#name\n",
    "    str3=i.split('_')[2]#说明书上的名字\n",
    "    str4=i.split('_')[3]#说明书上的群系编号\n",
    "    #csv名称\n",
    "    str8=str4+ '_' +str3+'_各类型信息统计'\n",
    "    str9=str4+ '_' +str3+'_分段拟合_各类型信息统计'\n",
    "    str6=0\n",
    "    #str6='椴、槭林'#输出二级分类的csv名\n",
    "  \n",
    "    if __name__ == \"__main__\":\n",
    "#         csvpath=r'F:\\2csv\\6121'#运行csv所在的文件夹，该程序运行的是该文件夹下的所有的csv文件\n",
    "        \n",
    "        L,name=file_name(csvpath)\n",
    "        path=csvpath+r'\\总体拟合'\n",
    "        if not os.path.exists(path):\n",
    "            os.mkdir(path)\n",
    "        else:\n",
    "            print('总体拟合文件夹已创建')\n",
    "        for str5 in name:\n",
    "            L=[]\n",
    "            print('\\n当前csv:'+str5)\n",
    "            if str5[:-4] == str8 or str5[:-4]==str9 :\n",
    "                continue\n",
    "\n",
    "####################植被小区的名字，改改改#################\n",
    "            str5_1=str5.split('.')[1]#大地域编号\n",
    "            str5_1='地域'+str5_1\n",
    "#########################################################\n",
    "\n",
    "            str5_2_1=str5.split('.')[0]#温度带\n",
    "            str5_3=str5.split('.')[2]#地域\n",
    "            str5_4=str5.split('.')[3].split('_')[0]#子类型\n",
    "                \n",
    "            temprList = ['温度交错带','高山极地带', '苔原带', '寒温带', '中温带', '暖温带', '亚热带', '热带','s22','s22']\n",
    "            \n",
    "            if str5_4 == '1123':\n",
    "                if str5_1=='':\n",
    "                    str7=str4+ '_' +str3+'_'+temprList[int(str5_2_1)]#输出图片名\n",
    "                else:\n",
    "                    str7=str4+ '_' +str3+'_'+temprList[int(str5_2_1)]+'_'+str5_1#输出图片名\n",
    "            else:\n",
    "                if str5_1=='':\n",
    "                    if str5_3=='0':\n",
    "                        str7=str4+ '_' +str3+'_'+temprList[int(str5_2_1)]+'_'+'类型'+str5_4#输出图片名\n",
    "                    else:\n",
    "                        str7=str4+ '_' +str3+'_'+temprList[int(str5_2_1)]+'-'+str5_3+'_'+'类型'+str5_4#输出图片名\n",
    "                else:\n",
    "                    if str5_3=='0':\n",
    "                        str7=str4+ '_' +str3+'_'+temprList[int(str5_2_1)]+ '_'+str5_1+'_'+'类型'+str5_4#输出图片名\n",
    "                    else:\n",
    "                        str7=str4+ '_' +str3+'_'+temprList[int(str5_2_1)]+ '_'+str5_1+'-'+str5_3+'_'+'类型'+str5_4#输出图片名\n",
    "            \n",
    "            tmix_list=[]\n",
    "            tmix_str=''\n",
    "            if str5_2_1 == '0':\n",
    "                tmix=str5.split('_')[1][:-4]\n",
    "                tmix_list=tmix.split('.')\n",
    "                for TL in range(len(tmix_list)):\n",
    "                    tmix_list[TL]  = temprList[int(tmix_list[TL])]\n",
    "                tmix_str='-'.join(tmix_list)\n",
    "                str7=str7.replace('温度',tmix_str)\n",
    "            \n",
    "            x, y,check,p_pe,p1_pe1,p2_pe2 ,p3_pe3,p4_pe4,p5_pe5,p6_pe6,p7_pe7,p8_pe8,p9_pe9,p10_pe10,p11_pe11,p12_pe12,total,p,pe,dem,tp_year= read_xy(csvpath+'/%s'%str5)\n",
    "\n",
    "            #检查data数据导出时命名是否正确\n",
    "            check_value = check[0]\n",
    "            if check_value != int(str1):\n",
    "                    print('value值和data数据内不一致')\n",
    "            all_value = data_process(x,y,0.05)\n",
    "            print('总样本点数：%d'%all_value['n'])\n",
    "            print('分区后的总样本点数：%d'%all_value['n_check'])\n",
    "            fig_opt = {'title': ('$%s$'+ ' '+u'%s'+str7.replace(str4+'_'+str3,'').replace('_',' '))%(str4,str3)}   \n",
    "            \n",
    "            #分类型拟合\n",
    "            fig, ax = plt.subplots(figsize = (17,13))\n",
    "            figure_drawing,regression2 = figure_drawing(x, y, 2,0.05,fig,ax, **fig_opt)\n",
    "            fig_save_address1=csvpath.replace('\\\\','/')+'/%s.png'\n",
    "            plt.savefig(fig_save_address1%str7,dpi = 300,bbox_inches='tight')\n",
    "            plt.clf()\n",
    "            plt.close('all')#清除当前画布，减少内存\n",
    "            \n",
    "            #总体拟合\n",
    "            fig, ax = plt.subplots(figsize = (17,13))\n",
    "            figure_drawing1,regression1 = figure_drawing(x, y, 1,0.05,fig,ax, **fig_opt)    \n",
    "            fig_save_address2=path.replace('\\\\','/')+'/%s.png'  \n",
    "            plt.savefig(fig_save_address2%(str7),dpi = 300,bbox_inches='tight')\n",
    "            plt.clf()\n",
    "            plt.close('all')\n",
    "            \n",
    "            if len(regression2)==1:\n",
    "                regression2.append(['/','/','/'])\n",
    "            csv_number+=all_value['n_check']\n",
    "            L=[str2,str1,str3,str4,total,all_value['n_check'],temprList[int(str5_2_1)].replace('温度',tmix_str),\n",
    "               str5_1[2:],str5_3,str5_4,\n",
    "               regression1[0][2].replace('$','').split('(')[0],regression1[0][0],regression1[0][1],judge_p(regression1[0][1]),\n",
    "               regression2[0][2].replace('$','').split('(')[0],regression2[0][0],regression2[0][1],judge_p(regression2[0][1]),\n",
    "               regression2[1][2].replace('$','').split('(')[0],regression2[1][0],regression2[1][1],judge_p(regression2[1][1]),\n",
    "              all_value['TB_max'],all_value['TB_min'],all_value['TB_mean'],all_value['TB_std'],\n",
    "              all_value['E_max'],all_value['E_min'],all_value['E_mean'],all_value['E_std'],\n",
    "              all_value['p_max'],all_value['p_min'],all_value['p_mean'],all_value['p_std'],\n",
    "              all_value['pe_max'],all_value['pe_min'],all_value['pe_mean'],all_value['pe_std'],\n",
    "              all_value['DEM_max'],all_value['DEM_min'],all_value['DEM_mean'],all_value['DEM_std'],\n",
    "              all_value['tp_year_max'],all_value['tp_year_min'],all_value['tp_year_mean'],all_value['tp_year_std']]\n",
    "            rows.append(L)\n",
    "\n",
    "if csv_number==total:\n",
    "    print('\\n各csv点数之和与该群系总点数相等')\n",
    "else:\n",
    "    print('\\n各csv点数之和与该群系总点数不相等,请检查:\\n1.该群系的所有csv是否同时跑了\\n2.是否有漏点情况')\n",
    "\n",
    "print('\\n开始生成信息统计csv\\n--------分割线--------')\n",
    "csv_save_address=csvpath.replace('\\\\','/')+'/%s.csv'\n",
    "with open(csv_save_address%str8,'w',newline='') as f1:\n",
    "    f1_csv = csv.writer(f1)\n",
    "    f1_csv.writerow(headers)\n",
    "    f1_csv.writerows(rows)\n",
    "print('write down')"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "分段拟合"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 60,
   "metadata": {
    "scrolled": false
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "输入当前文件夹目录下需要进行分段拟合的csv名称，示例:6.1.0.3\n",
      "1.303.0.1\n",
      "总样本点数：60229\n",
      "分区后的总样本点数：173\n",
      "请输入分界点1的横坐标20\n",
      "请输入分界点1的纵坐标220\n",
      "请输入分界点2的横坐标18\n",
      "请输入分界点2的纵坐标-190\n",
      "当前分界线是否合适(1为合适,0为不合适)1\n",
      "是否仍需进行分段拟合:0\n",
      "\n",
      "开始生成分段拟合信息统计csv\n",
      "--------分割线--------\n"
     ]
    }
   ],
   "source": [
    "#####################################分段拟合####################################\n",
    "TSL='1'\n",
    "headers1=['name','value','说明书名字','说明书群系编号','总样本点数','分区后总样本点数','温度带','区域','小地域','类型',\n",
    "         '分界点1坐标','分界点2坐标',\n",
    "         '第一段回归方程','R方','P值','P值范围',\n",
    "         '第二段回归方程','R方','P值','P值范围',\n",
    "        'TB_max','TB_min','TB_mean','TB_std',\n",
    "        'E_max','E_min','E_mean','E_std',\n",
    "        'p_max','p_min','p_mean','p_std',\n",
    "        'pe_max','pe_min','pe_mean','pe_std',\n",
    "        'dem_max','dem_min','dem_mean','dem_std',\n",
    "        'tp_year_max','tp_year_min','tp_year_mean','tp_year_std']\n",
    "rows1=[]\n",
    "TS_path=csvpath+r'\\分段拟合'\n",
    "if not os.path.exists(TS_path):\n",
    "    os.mkdir(TS_path)\n",
    "else:\n",
    "    print('分段拟合文件夹已创建')\n",
    "\n",
    "##自行选取csv进行拟合\n",
    "while TSL=='1':\n",
    "    L=[]\n",
    "\n",
    "    str5=input('输入当前文件夹目录下需要进行分段拟合的csv名称，示例:6.1.0.3\\n')+'.csv'\n",
    "    \n",
    "    str5_1=str5.split('.')[1]#大地域编号\n",
    "    str5_1='地域'+str5_1\n",
    "    str5_2_1=str5.split('.')[0]#温度带\n",
    "    str5_3=str5.split('.')[2]#地域\n",
    "    str5_4=str5.split('.')[3].split('_')[0]#子类型\n",
    "                \n",
    "    temprList = ['温度交错带','高山极地带', '苔原带', '寒温带', '中温带', '暖温带', '亚热带', '热带']\n",
    "            \n",
    "    if str5_4 == '0':\n",
    "        if str5_1=='':\n",
    "            str7=str4+ '_' +str3+'_'+temprList[int(str5_2_1)]#输出图片名\n",
    "        else:\n",
    "            str7=str4+ '_' +str3+'_'+temprList[int(str5_2_1)]+'_'+str5_1#输出图片名\n",
    "    else:\n",
    "        if str5_1=='':\n",
    "            if str5_3=='0':\n",
    "                str7=str4+ '_' +str3+'_'+temprList[int(str5_2_1)]+'_'+'类型'+str5_4#输出图片名\n",
    "            else:\n",
    "                str7=str4+ '_' +str3+'_'+temprList[int(str5_2_1)]+'-'+str5_3+'_'+'类型'+str5_4#输出图片名\n",
    "        else:\n",
    "            if str5_3=='0':\n",
    "                str7=str4+ '_' +str3+'_'+temprList[int(str5_2_1)]+ '_'+str5_1+'_'+'类型'+str5_4#输出图片名\n",
    "            else:\n",
    "                str7=str4+ '_' +str3+'_'+temprList[int(str5_2_1)]+ '_'+str5_1+'-'+str5_3+'_'+'类型'+str5_4#输出图片名\n",
    "            \n",
    "    tmix_list=[]\n",
    "    tmix_str=''\n",
    "    if str5_2_1 == '0':\n",
    "        tmix=str5.split('_')[1][:-4]\n",
    "        tmix_list=tmix.split('.')\n",
    "        for TL in range(len(tmix_list)):\n",
    "            tmix_list[TL]  = temprList[int(tmix_list[TL])]\n",
    "        tmix_str='-'.join(tmix_list)\n",
    "        str7=str7.replace('温度',tmix_str)\n",
    "    \n",
    "    #读取数据\n",
    "    x, y,check,p_pe,p1_pe1,p2_pe2 ,p3_pe3,p4_pe4,p5_pe5,p6_pe6,p7_pe7,p8_pe8,p9_pe9,p10_pe10,p11_pe11,p12_pe12,total,p,pe,dem,tp_year= read_xy(csvpath+'/%s'%str5)\n",
    "    check_value = check[0]\n",
    "    print('总样本点数：%d'%all_value['n'])\n",
    "    print('分区后的总样本点数：%d'%all_value['n_check'])    \n",
    "    fig_opt = {'title': ('$%s$'+ ' '+u'%s'+str7.replace(str4+'_'+str3,'').replace('_',' '))%(str4,str3)}   \n",
    "    control_fd=0\n",
    "    while control_fd==0:\n",
    "        \n",
    "    #分类型拟合\n",
    "        fig, ax = plt.subplots(figsize = (17,13))\n",
    "\n",
    "        figure_drawing,regression2 = figure_drawing(x, y, TSL,0.05,fig,ax, **fig_opt)\n",
    "        fig_save_address1=TS_path.replace('\\\\','/')+'/%s.png'\n",
    "        plt.savefig(fig_save_address1%str7,dpi = 300,bbox_inches='tight')    \n",
    "        plt.clf()\n",
    "        plt.close('all')#清除当前画布，减少内存\n",
    "    \n",
    "        control_fd=int(input('当前分界线是否合适(1为合适,0为不合适)'))\n",
    "    L=[str2,str1,str3,str4,total,all_value['n_check'],temprList[int(str5_2_1)].replace('温度',tmix_str),\n",
    "       str5_1[2:],str5_3,str5_4,\n",
    "       '('+str(x_1)+','+str(y_1)+')','('+str(x_2)+','+str(y_2)+')',\n",
    "       regression2[0][2].replace('$','').split('(')[0][:-3],regression2[0][0],regression2[0][1],judge_p(regression2[0][1]),\n",
    "       regression2[1][2].replace('$','').split('(')[0][:-3],regression2[1][0],regression2[1][1],judge_p(regression2[1][1]),\n",
    "       all_value['TB_max'],all_value['TB_min'],all_value['TB_mean'],all_value['TB_std'],\n",
    "       all_value['E_max'],all_value['E_min'],all_value['E_mean'],all_value['E_std'],\n",
    "       all_value['p_max'],all_value['p_min'],all_value['p_mean'],all_value['p_std'],\n",
    "       all_value['pe_max'],all_value['pe_min'],all_value['pe_mean'],all_value['pe_std'],\n",
    "       all_value['DEM_max'],all_value['DEM_min'],all_value['DEM_mean'],all_value['DEM_std'],\n",
    "       all_value['tp_year_max'],all_value['tp_year_min'],all_value['tp_year_mean'],all_value['tp_year_std']]\n",
    "    rows1.append(L)\n",
    "    TSL=input('是否仍需进行分段拟合:')\n",
    "\n",
    "\n",
    "print('\\n开始生成分段拟合信息统计csv\\n--------分割线--------')\n",
    "csv_save_address=TS_path.replace('\\\\','/')+'/%s.csv'\n",
    "with open(csv_save_address%str9,'w',newline='') as f1:\n",
    "    f1_csv = csv.writer(f1)\n",
    "    f1_csv.writerow(headers1)\n",
    "    f1_csv.writerows(rows1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.7.3"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
